package com.amon.amonplayer.crash;

import android.app.Activity;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class ActivityManager {
    private volatile boolean isForeground = true;
    @NonNull
    private final WeakStack<Activity> mActivityStack = new WeakStack<>();

    public ActivityManager() {
        LifecycleCallback.getInstance().register(new IForeBackInterface(){

            @Override
            public void onForeground(Activity activity) {
                isForeground = true;
            }

            @Override
            public void onBackground(Activity activity) {

            }

            @Override
            public void onCreate(Activity activity) {
                mActivityStack.add(activity);
            }

            @Override
            public void onResume(Activity activity) {

            }

            @Override
            public void onStop(Activity activity) {

            }

            @Override
            public void onDestroy(Activity activity) {
                synchronized (mActivityStack) {
                    mActivityStack.remove(activity);
                    mActivityStack.notify();
                }
            }
        });
    }

    /**
     * 从集合中取出最后一个activity返回.
     *
     * @return last created activity, if any
     */
    @Nullable
    public Activity getLastActivity() {
        return mActivityStack.peek();
    }

    /**
     * 获取所有未销毁activity的集合.
     *
     * @return a list of activities in the current process
     */
    @NonNull
    public List<Activity> getLastActivities() {
        return new ArrayList<>(mActivityStack);
    }

    /**
     * clear saved activities.
     */
    public void clearLastActivities() {
        mActivityStack.clear();
    }

    /**
     * wait until the last activity is stopped.
     *
     * @param timeOutInMillis timeout for wait
     */
    public void waitForAllActivitiesDestroy(int timeOutInMillis) {
        synchronized (mActivityStack) {
            long start = System.currentTimeMillis();
            long now = start;
            while (!mActivityStack.isEmpty() && start + timeOutInMillis > now) {
                try {
                    mActivityStack.wait(start - now + timeOutInMillis);
                } catch (InterruptedException ignored) {
                    Log.w("LOG_TAG", "activityStack wait may be error");
                }
                now = System.currentTimeMillis();
            }
            Log.i("LOG_TAG", "now killed all activities.");
        }
    }

    /**
     * 判断crash时Activity的前后台状态
     *
     * @return true为前台，false为后台
     */
    public boolean isForeground() {
        return isForeground;
    }
}
